import { defineStore } from 'pinia'
import { login, getUserInfo, register as registerApi } from '@/api/user'
import { ElMessage } from 'element-plus'
import router from '@/router'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: {},
    isLogin: !!localStorage.getItem('token')
  }),

  actions: {
    // 用户注册
    async register(registerData: any) {
      try {
        const response = await registerApi(registerData)
        if (response.code === 200) {
          ElMessage.success('注册成功，请登录')
          return true
        }
        return false
      } catch (error) {
        console.error('注册失败:', error)
        return false
      }
    },

    // 用户登录
    async login(userInfo: { username: string; password: string }) {
      try {
        const response = await login(userInfo)
        if (response.code === 200) {
          const { token } = response.data
          localStorage.setItem('token', token)
          this.token = token
          this.isLogin = true

          // 获取用户信息
          await this.getUserInfo()

          ElMessage.success('登录成功')
          // 使用 nextTick 确保在DOM更新后再进行路由跳转
          await router.push('/user/products')
          console.log('路由跳转完成: /user/products')
          return true
        }
        // 不在这里处理错误消息，由响应拦截器统一处理
        return false
      } catch (error) {
        console.error('登录失败:', error)
        // 不在这里处理错误消息，由响应拦截器统一处理
        return false
      }
    },

    // 获取用户信息
    async getUserInfo() {
      try {
        const response = await getUserInfo()
        if (response.code === 200) {
          this.userInfo = response.data
          return response.data
        }
        return null
      } catch (error) {
        console.error('获取用户信息失败:', error)
        return null
      }
    },

    // 退出登录
    logout() {
      localStorage.removeItem('token')
      // 不删除保存的用户名，以便下次登录时自动填充
      this.token = ''
      this.userInfo = {}
      this.isLogin = false
      router.push('/login')
      ElMessage.success('退出登录成功')
    }
  }
})
